//
//  UIView+KSObjc.m
//  KSObjcUtilDemo
//
//  Created by 孔 on 2023/5/30.
//  Copyright © 2023 kong. All rights reserved.
//

#import "UIView+KSObjc.h"
#import <objc/runtime.h>

@implementation UIView (KSObjc)
- (void)setCornerRadius:(CGFloat)cornerRadius {
    self.layer.cornerRadius = cornerRadius;
}
- (CGFloat)cornerRadius {
    return self.layer.cornerRadius;
}

- (void)setMaskedCorners:(NSUInteger)maskedCorners {
    self.layer.maskedCorners = maskedCorners;
}
- (NSUInteger)maskedCorners {
    return self.layer.maskedCorners;
}

- (UIColor*)borderColor {
    return [UIColor colorWithCGColor:self.layer.borderColor];
}

- (void)setBorderColor:(UIColor *)borderColor{
    self.layer.borderColor = borderColor.CGColor;
}
- (void)setBorderWidth:(CGFloat)borderWidth {
    self.layer.borderWidth = borderWidth;
}
- (CGFloat)borderWidth {
    return self.layer.borderWidth;
}

+ (instancetype)viewFromXib{
    NSString* name = NSStringFromClass([self class]);
    return [[[NSBundle mainBundle] loadNibNamed:name owner:self options:nil] lastObject];
}

- (UIImage*)captureRect:(CGRect)rect{
    UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage *bgImage = UIGraphicsGetImageFromCurrentImageContext();
    CGImageRef subimageRef = CGImageCreateWithImageInRect(bgImage.CGImage, rect);
    UIImage *subImage = [UIImage imageWithCGImage:subimageRef];
    
    UIGraphicsEndImageContext();
    return subImage;
}

- (void)addGesture:(UIGestureRecognizer*)gesture withBlock:(void(^)(UIGestureRecognizer * _Nonnull recognizer))block{
    static int _ks_selector_block_id = 0;
    NSString *selectorName = [NSString stringWithFormat:@"ks_gesture_selector%d:",++_ks_selector_block_id];
    IMP implementation = imp_implementationWithBlock(block);
    SEL newSelector = NSSelectorFromString(selectorName);
    class_addMethod([self class], newSelector, implementation, "v@:@");
    [gesture addTarget:self action:newSelector];
    [self addGestureRecognizer:gesture];
}

- (void)addTapGestureWithBlock:(void (^)(UIGestureRecognizer * _Nonnull recognizer))tapBlock{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [self addGesture:tap withBlock:^(UIGestureRecognizer * _Nonnull recognizer) {
        !tapBlock?:tapBlock(recognizer);
    }];
}

@end
